package com.ynet.middleground.oss.common;

import org.springframework.core.annotation.Order;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.common.base.Throwables;
import com.ynet.core.common.ServiceResult;
import com.ynet.core.log.IfpLogger;

/**
 * @author liulx
 * @description 参数异常统一处理
 * @date 2020-10-19 10:28
 */
@Order(1)
@ControllerAdvice
public class ValidationException {

    @ResponseBody
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ServiceResult validationException(MethodArgumentNotValidException exception) {
        BindingResult bindingResult = exception.getBindingResult();
        IfpLogger.error(Thread.currentThread().getStackTrace()[1].getMethodName(), "参数异常, case: {}",
            Throwables.getStackTraceAsString(exception));
        ServiceResult<Object> result = new ServiceResult<>();
        if (bindingResult.hasErrors()) {
            String defaultMessage = bindingResult.getFieldError().getDefaultMessage();
            result.setError("ECOS0001", defaultMessage);
        } else {
            result.setError("ECOS0000", exception.getMessage());
        }
        return result;
    }

}
